package com.machine.dao.user.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.machine.bean.Componentpart;
import com.machine.dao.user.ComponentDao;

@Component(value = "componentDao")
@Transactional
public class ComponentDaoImpl implements ComponentDao {

	private SessionFactory sessionfactory;

	public SessionFactory getSessionfactory() {
		return sessionfactory;
	}

	@Resource
	public void setSessionfactory(SessionFactory sessionfactory) {
		this.sessionfactory = sessionfactory;
	}

	@Override
	public void add(com.machine.bean.Componentpart component) {
		sessionfactory.getCurrentSession().save(component);
	}

	@Override
	public int delete(com.machine.bean.Componentpart component) {
		sessionfactory.getCurrentSession().delete(component);
		return 1;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<com.machine.bean.Componentpart> find(String name) {
		String hql = "from Componentpart componentpart where componentpart.name like '%"
				+ name + "%' order by componentpart.price";
		Session session = sessionfactory.getCurrentSession();
		Query query = session.createQuery(hql);
		List<com.machine.bean.Componentpart> comList = query.list();
		return comList;
	}

	@Override
	public int update(com.machine.bean.Componentpart component) {
		sessionfactory.getCurrentSession().update(component);
		return 1;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Componentpart> findAll() {
		String hql = "from Componentpart componentpart";
		Session session = sessionfactory.getCurrentSession();
		Query query = session.createQuery(hql);
		List<com.machine.bean.Componentpart> comList = query.list();
		return comList;
	}

	@Override
	public int deleteByIdList(List<Integer> idList) {
		Componentpart component = null;
		for (Integer id : idList) {
			component = new Componentpart();
			component.setId(id);
			sessionfactory.getCurrentSession().delete(component);
		}
		return 1;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Componentpart findById(Integer id) {
		String hql = "from Componentpart componentpart where componentpart.id ="
				+ id + " ";
		Session session = sessionfactory.getCurrentSession();
		Query query = session.createQuery(hql);
		List<com.machine.bean.Componentpart > comList = query.list();
		if (comList.size() > 0) {
			return comList.get(0);
		}
		return null;
	}

}
